package com.emser.unc.client.presenter;

import java.util.ArrayList;

import com.emser.unc.client.CloudMobile;
import com.emser.unc.client.event.AdminSaleReportEvent;
import com.emser.unc.client.helper.RPCCall;
import com.emser.unc.client.service.CustomerService;
import com.emser.unc.client.service.CustomerServiceAsync;
import com.emser.unc.client.service.ReportsService;
import com.emser.unc.client.service.ReportsServiceAsync;
import com.emser.unc.client.service.SellerService;
import com.emser.unc.client.service.SellerServiceAsync;
import com.emser.unc.serializable.CustomerDTO;
import com.emser.unc.serializable.ProductSoldDTO;
import com.emser.unc.serializable.ResultDTO;
import com.emser.unc.serializable.SellerDTO;
import com.emser.unc.serializable.UserAccountDTO;
import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.event.dom.client.HasClickHandlers;
import com.google.gwt.event.shared.SimpleEventBus;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.HasText;
import com.google.gwt.user.client.ui.HasWidgets;
import com.google.gwt.user.client.ui.Widget;
import com.google.gwt.view.client.HasData;
import com.google.gwt.view.client.RangeChangeEvent;

public class SaleReportDetailPresenter implements Presenter{
	private final Display display;
	private SellerServiceAsync rpcServiceSeller;
	private CustomerServiceAsync rpcCustomerService;
	private ReportsServiceAsync rpcReportService;
	private UserAccountDTO userA;
	private String sellerUName;
	private Long customerId;
	private Long reportId;
	private int rangeStart;
	private int pageSize = CloudMobile.constants.pageSizeCP();
	private SimpleEventBus eventBus;
	private ArrayList<String> cursors = new ArrayList<String>();
	private int pageNum;
	private String pageCursor;
	
	public interface Display {	
	    Widget asWidget();
	    HasClickHandlers getGoBackButton();
		HasData<ProductSoldDTO> getTable();
		HasText getSellerName();
	    HasText getSellerAddress();
	    HasText getSellerTelephone();
	    HasText getSellerUName();
	    HasText getCustomerName();
	    HasText getCustomerAddress();
	    HasText getCustomerTelephone();
	    HasText getCustomerID();
	    void enableMsgCDeleted(boolean enable);
	    void enableMsgSDeleted(boolean enable);
	    void showBusyIndicator();
		void hideBusyIndicator();
		void setPage(int page);
		int getPage();
	  }
	public SaleReportDetailPresenter(UserAccountDTO user,SimpleEventBus eventBus,Display display){
		this.display = display;
		this.rpcCustomerService = GWT.create(CustomerService.class);
		this.rpcServiceSeller = GWT.create(SellerService.class);
		this.rpcReportService = GWT.create(ReportsService.class);
		this.userA = user;
		this.eventBus = eventBus;
		this.rangeStart = 0;
		cursors.add(null);
		bind();
	}
	private void bind() {
		this.display.getGoBackButton().addClickHandler(new ClickHandler() {   
		      public void onClick(ClickEvent event) {
		    	  eventBus.fireEvent(new AdminSaleReportEvent());
		      }
		});
		this.display.getTable().addRangeChangeHandler(new RangeChangeEvent.Handler() {
	        @Override
	        public void onRangeChange(RangeChangeEvent event) {
	        	doChangeRange();
	    }});
	}
	private void doChangeRange() {
		populateProductSoldList();	
	}
	private void populateProductSoldList() {
		rangeStart = display.getTable().getVisibleRange().getStart();
		display.showBusyIndicator();
		pageNum = display.getPage();
		try{
			pageCursor = cursors.get(pageNum);
		}
		catch(Exception e){
			pageCursor = null;
		}
		new RPCCall<ResultDTO<ProductSoldDTO>>(){
			@Override
			public void onFailure(Throwable caught) {
				display.hideBusyIndicator();
				Window.alert(CloudMobile.constants.eGetProducts());	
			}
			@Override
			public void onSuccess(ResultDTO<ProductSoldDTO> result) {
				display.hideBusyIndicator();
				try{
					pageCursor = cursors.get(pageNum+1);
				}
				catch(Exception e){
					pageCursor = null;
				}
				if(result != null){
						if(pageCursor == null)
							cursors.add(result.getCursorString());
						display.getTable().setRowData(rangeStart, result.getList());
				}
			}
			@Override
			protected void callService(AsyncCallback<ResultDTO<ProductSoldDTO>> cb) {
				rpcReportService.getProductsSold(pageCursor,pageSize,reportId,userA.getName(),cb);	
			}
		}.retry(3);
	}
	@Override
	public void go(HasWidgets container) {
		container.clear();
		container.add(display.asWidget());
		getSeller();
		getCustomer();
		updateRowCount();
	}
	
	private void getSeller(){
		new RPCCall<SellerDTO>(){
			@Override
			public void onFailure(Throwable caught) {
				Window.alert(CloudMobile.constants.eGetSellers());	
			}
			@Override
			public void onSuccess(SellerDTO result) {
				if(result == null){
					clearInfoSeller();
					display.getSellerUName().setText(sellerUName);
					display.enableMsgSDeleted(true);
				}
				else
					setInfoSeller(result);
			}
			@Override
			protected void callService(AsyncCallback<SellerDTO> cb) {
				rpcServiceSeller.getSeller(sellerUName, userA.getName(), cb);	
			}
		}.retry(3);
		
	}
	
	protected void setInfoSeller(SellerDTO seller) {
		display.getSellerUName().setText(seller.getUserName());
		display.getSellerName().setText(seller.getFirstName()+" "+seller.getLastName());
		display.getSellerAddress().setText(seller.getAddress());
		display.getSellerTelephone().setText(seller.getTelephone());	
	}
	
	protected void clearInfoSeller() {
		display.getSellerUName().setText("");
		display.getSellerName().setText("");
		display.getSellerAddress().setText("");
		display.getSellerTelephone().setText("");	
	}
	
	protected void clearInfoCustomer() {
		display.getCustomerID().setText("");
		display.getCustomerName().setText("");
		display.getCustomerAddress().setText("");
		display.getCustomerTelephone().setText("");	
	}
	
	private void getCustomer(){
		new RPCCall<CustomerDTO>(){
			@Override
			public void onFailure(Throwable caught) {
				Window.alert(CloudMobile.constants.eGetSellers());	
			}
			@Override
			public void onSuccess(CustomerDTO result) {
				if(result == null){
					clearInfoCustomer();
					display.getCustomerID().setText(customerId.toString());
					display.enableMsgCDeleted(true);
				}else
					setInfoCustomer(result);
				
			}
			@Override
			protected void callService(AsyncCallback<CustomerDTO> cb) {
				rpcCustomerService.getCustomer(customerId, userA.getName(), cb);	
			}
		}.retry(3);
	}
	
	private void setInfoCustomer(CustomerDTO customer) {
		display.getCustomerID().setText(customer.getCode().toString());
		display.getCustomerName().setText(customer.getFirstName()+" "+customer.getLastName());
		display.getCustomerAddress().setText(customer.getAddress());
		display.getCustomerTelephone().setText(customer.getTelephone());
		
	}
	
	private void updateRowCount(){
		new RPCCall<Integer>(){
			@Override
			public void onFailure(Throwable caught) {
				Window.alert(CloudMobile.constants.eGetCountCustomers());
			}
			@Override
			public void onSuccess(Integer result) {
				if(result != null){
					display.getTable().setRowCount(result,true);
					if(result>0)
						populateProductSoldList();	
				}	
			}
			@Override
			protected void callService(AsyncCallback<Integer> cb) {	
				rpcReportService.getProductsSoldsCount(userA.getName(), reportId, cb);
			}
		}.retry(3);	 	
	}
	public void setUserNSeller(String userNSeller) {
		this.sellerUName = userNSeller;
	}
	public String getUserNSeller() {
		return sellerUName;
	}
	public void setIdCustomer(Long idCustomer) {
		this.customerId = idCustomer;
	}
	public Long getIdCustomer() {
		return customerId;
	}
	public void setIdReport(Long idReport) {
		this.reportId = idReport;
	}
	public Long getIdReport() {
		return reportId;
	}
	

}
